/* -------------------------------------------------------------------------- *
   TestWinUnit - Maria Blees (maria.blees@microsoft.com)

   File: ReadableTempFile.h
   This file/class is a specialization of TempFile that allows reading the 
   contents of the file.
 * -------------------------------------------------------------------------- */
#pragma once

#include "TempFile.h"

#include <stdio.h>

class ReadableTempFile : public TempFile
{
private:
    FILE* _file;
public:
    ReadableTempFile();
    ~ReadableTempFile();

    // This function reads a line from the file, assuming it's a non-Unicode 
    // text file.  For my purposes, this is okay, because I'm using this file to 
    // capture console output.
    // Per the MSDN article "Unicode Stream I/O in Text and Binary Mode"
    // ( http://msdn2.microsoft.com/en-us/library/c4cy2b8e(VS.80).aspx ),
    // writes to console by default are expected to be non-Unicode.  
    // Since I never changed my stderr or stdout (that I'm capturing, from my app)
    // to binary, I know that they are written to as non-Unicode text.

    char* ReadLine(char* buffer, DWORD bufferSize, size_t& charsRead, bool& truncated);
};

// This class is for convenience so caller does not have to allocate a buffer. 
template<int BUFFERSIZE>
class ReadableTempFileT : public ReadableTempFile
{
private:
    char _buffer[BUFFERSIZE];
public:
    // I'm explicitly ignoring the EOF or truncation cases, as I don't really
    // care--I just want to see the output (if the output is blank, that is
    // also a problem).  Not returning NULL here made one fewer check necessary
    // in the caller.
    const char* ReadNonEmptyLine()
    {
        size_t charsRead = 0;
        bool truncated = false;

        // Return the first line with length > 0
        char* line = NULL;

        for (line = ReadLine(_buffer, (DWORD)BUFFERSIZE, charsRead, truncated);
             line != NULL && charsRead == 0;
             line = ReadLine(_buffer, (DWORD)BUFFERSIZE, charsRead, truncated));

        return (line == NULL ? "" : line);
    }
};